﻿using Gengens.Disk.Repository;
using Gengens.Disk.Service;
using Serilog;
using System.Reflection;

namespace Gengens.Disk.WebApi.util
{
    public static class IocExtends
    {
        public static void RegisterRepository(this IServiceCollection services)
            => services.RegisterByBaseType(MateData.RepositoryAssmblys,typeof(BaseRepository<>));

        public static void RegisterService(this IServiceCollection services)
            => services.RegisterByBaseType(MateData.ServiceAssmblys, typeof(BaseService<>));

        public static void RegisterByBaseType(this IServiceCollection services,List<Assembly> assemblys,Type baseType) {
            string baseTypeFullName = baseType.GetGenericTypeDefinition().FullName;
            var items = assemblys.SelectMany(a => a.GetTypes()).ToList().FindAll(t =>
                {
                    var theBase = t.BaseType;
                    if (theBase == default) return false;
                    if (!theBase.IsGenericType) return false;
                    return theBase.GetGenericTypeDefinition().FullName == baseTypeFullName;
                }
            );
            foreach (var item in items)
            {
                services.AddTransient(item);
                Log.Information("IOC容器已添加：" + item.FullName);
            }
        }
    }
}
